<?php
namespace cms\modules\frontend\controllers;

use Yii;
use yii\helpers\Html;
use yii\db\Expression;
use app\models\ContentCategory;
use app\models\ContentCategorySearch;
use app\models\Content;
use app\models\ContentSearch;
use app\models\ContentAttrRelationships;
use app\models\ContentCategoryAttr;
use app\models\CategoryAttrRelationships;
use app\models\TagsRelationships;
use app\models\MemberStar;
use common\component\tool\Tool;
use common\component\exception\ErrMap;


class ContentController extends AuthController
{
	/*内容栏目*/
    public function actionCategory()
    {
        $this->get['app_id'] = $this->app_id;
        // P($this->get);
        $search = (new ContentCategorySearch())->search($this->get);
        if($search === false){//验证搜索参数不通过
            $count = 0;
            $contentCategoryList = array();
        }else{
            if(isset($this->get['type']) and $this->get['type'] == 'ele'){
                $flag = 'ele';
            }else{
                $flag = '';
            }
            if(isset( $this->get['parentid'] )){
                $parentid = $this->get['parentid'];
            }else{
                $parentid = 0;
            }
            // P($search);
            $contentCategoryList = ContentCategory::getTreeList($search, $flag, $parentid);
        }
        // P($contentCategoryList);
        return Tool::showRes([0, '获取成功'], $contentCategoryList);
    }


    /*列表*/
    public function actionContentList()
    {
        if(isset($this->get['catid'])){
            /*取出分类数据*/
            $category = ContentCategory::find()
                        ->select(['catid', 'name', 'alias', 'icon', 'preview'])
                        ->where('catid = :catid', [':catid' => $this->get['catid']])
                        ->asArray()->one();
            // P($category);

            if(isset($this->get['page'])){
                $currPage = intval($this->get['page']?$this->get['page']:1);
            }else{
                $currPage = 1;
            }
            if(isset($this->get['pagesize'])){
                $pageSize = intval($this->get['pagesize']?$this->get['pagesize']:Tool::getPageSize());
            }else{
                $pageSize = Tool::getPageSize();
            }
            if(isset($this->get['haschild']) and $this->get['haschild'] == 2){
                /*所有所有子类ID*/
                $childIds = [$this->get['catid']];
                $res = ContentCategory::find()
                        ->select('catid')
                        ->where(new Expression("FIND_IN_SET(:catid, allparentid)", [":catid"=>$this->get['catid']]))
                        ->asArray()->all();
                // P($res);
                if(!is_null($res)){
                    foreach($res as $k => $v){
                        array_push($childIds, $v['catid']);
                    }
                }
                // P(implode(',', $childIds));
                $haschildWhere = ' or catid in (' . implode(',', $childIds) . ')';
                // P($haschildWhere);
            }else{
                $haschildWhere = '';
            }
            // P($haschildWhere);
            $this->get['hassamelevel'] = 1;//为了获取同级的内容
            $this->get['app_id'] = $this->app_id;
            // P($this->get);
            $search = (new ContentSearch())->search($this->get);
            $searchCount = (new ContentSearch())->search($this->get);//
            // P($search);
            if($search === false){//验证搜索参数不通过
                $count = 0;
                $contentList = array();
            }else{
                $count = $searchCount
                ->andWhere('state = 3 and display = 2')
                ->andWhere(new Expression("FIND_IN_SET(:catid, catids)", [":catid"=>$this->get['catid']]))
                ->count();
                // P($search);
                $contentList = $search->select(['content_id', 'title', 'preview', 'outside', 'url_target', 'outside_url', 'describe', 'star_num', 'praise_num', 'reply_num', 'member_view', 'pc_preview_count', 'mobile_preview_count', 'add_time'])
                              ->andWhere('state = 3 and display = 2')
                              ->andWhere(new Expression("FIND_IN_SET(:catid, catids)" . $haschildWhere, [":catid"=>$this->get['catid']]))
                              ->offset($pageSize*($currPage-1))->limit($pageSize)
                              ->orderBy([
                                    'istop' => SORT_DESC,
                                    'toptime' => SORT_DESC,
                                    'sort' => SORT_DESC,
                                    'add_time' => SORT_DESC
                                ])
                              // ->createCommand()->getRawSql();
                              ->asArray()->all();
                // P($contentList);
                
                $contentids = '';//收集所有内容ID 为了获取
                foreach($contentList as $k => $v){
                    if(!empty($v['preview'])){
                        $contentList[$k]['preview'] = explode(',', $v['preview']);
                    }
                    $contentids .= $v['content_id'] . ",";
                }
                // P($contentids);

                /*取出该类中，对应的自定义字段*/
                $categoryAttrRelationships = CategoryAttrRelationships::find()
                                                ->where('unionid = :id', [':id' => $this->get['catid']])
                                                ->joinWith('attrName')
                                                ->asArray()->all();
                // P($categoryAttrRelationships);
                /*把该类中 所有的自定义字段，放到内容列表中，目前是没有数据的*/
                foreach($contentList as $k => $v){
                    foreach($categoryAttrRelationships as $k1 => $v1){
                        $contentList[$k][$v1['attrName']['attr_enname']] = '';
                    }
                }
                // P($contentList);

                /*取出所有内容对应的 自定义字段内容*/
                if(!empty($contentids)){
                    $contentids = rtrim($contentids, ",");
                    $contentids = explode(',', $contentids);
                }
                // P($contentids);
                $contentAttrRelationships = ContentAttrRelationships::find()
                                            ->where(['in', 'content_id', $contentids])
                                            ->joinWith('attrName')
                                            ->asArray()->all();
                // P($contentAttrRelationships);

                /*把字段放到列表中*/
                foreach($contentList as $k => $v){
                    foreach($contentAttrRelationships as $k1 => $v1){
                        if($v['content_id'] == $v1['content_id']){
                            $contentList[$k][$v1['attrName']['attr_enname']] = $v1['attr_value'];
                        }
                    }
                }

            }
            // P($contentids, false);
            // P($contentList);
            $res = array(
                'list' => $contentList,
                'category' => $category,
                'pageInfo' => array(
                    'count' => intval($count),
                    'currPage' => $currPage,
                    'pageSize' => $pageSize,
                ),
            );
            // P($res);
            return Tool::showRes([0, '获取成功'], $res);
        }

        return Tool::showRes(ErrMap::getError(10005));
    }


    /*详情*/
    public function actionDetails()
    {
        /*如果有openid, 则可以获取用户信息，实现登录  主要是为了内容的收藏、点赞*/
        if(!$this->isLogin() 
            and isset($this->get['openid'])){
            $this->getinfoByOpenid($this->get['openid'], $this->comid);
        }

        /*取出单个数据*/
        if(Yii::$app->request->isGet){
            // P($this->get);
            $catid = isset($this->get['catid'])?$this->get['catid']:'';
            $content_id = isset($this->get['id'])?$this->get['id']:'';
            if($catid or $content_id){
                if($content_id){
                    $content = Content::find()
                            ->select(['content_id as id', 'catids', 'title', 'preview', 'describe', 'content', 'star_num', 'praise_num', 'add_time'])
                            ->where('content_id = :cid and display = 2 and state = 3', [':cid' => $content_id])
                            ->asArray()->one();
                }else{
                    $content = Content::find()
                            ->select(['content_id', 'catids', 'title', 'preview', 'describe', 'content', 'star_num', 'praise_num', 'add_time'])
                            ->where('catids = :cid and display = 2 and state = 3', [':cid' => $catid])
                            ->orderBy(['content_id' => SORT_DESC])
                            ->asArray()->one();
                    $content_id = $content['content_id'];
                    // P($content_id);
                }
                // P($content);
                if(!is_null($content)){
                    if(!empty($content['preview'])){
                        $content['preview'] = explode(',', $content['preview']);
                    }else{
                        $content['preview'] = [];
                    }
                    if(!empty($content['content'])){
                        $content['content'] = Html::decode($content['content']);
                    }

                    /*获取标签*/
                    $tagsRelationships = TagsRelationships::find()
                                ->select('unionid, {{%tags_relationships}}.tid')
                                ->joinWith('tag')
                                ->where('{{%tags_relationships}}.app_id = :app_id and unionid = :unionid', [':app_id' => $this->app_id, ':unionid' => $content_id])
                                // ->createCommand()->getRawSql();
                                ->asArray()->all();
                    // echo $this->app_id . '-' .  $content_id;
                    // P($tagsRelationships);
                    if(!is_null($tagsRelationships)){
                        $content['tag'] = [];
                        foreach($tagsRelationships as $k => $v){
                            array_push($content['tag'], $v['tag']['tag_name']);
                        }
                    }

                    /*获取自定义字段*/
                    $contentAttrRelationships = ContentAttrRelationships::find()
                                ->select('content_id, {{%content_attr_relationships}}.attr_id, {{%content_attr_relationships}}.attr_value')
                                ->joinWith('attrName')
                                ->where('{{%content_attr_relationships}}.app_id = :app_id and content_id = :id', [':app_id' => $this->app_id, ':id' => $content_id])
                                ->asArray()->all();
                    if(!is_null($contentAttrRelationships)){
                        foreach($contentAttrRelationships as $k => $v){
                            /*多选的，需要转成数组*/
                            if($v['attrName']['attr_type'] == 2 or $v['attrName']['attr_type'] == 4 or $v['attrName']['attr_type'] == 7){
                                $contentAttrRelationships[$k]['attr_value'] = json_decode($v['attr_value']);
                            }
                            /*编辑器，需要转义*/
                            if($v['attrName']['attr_type'] == 6){
                                $contentAttrRelationships[$k]['attr_value'] = Html::decode($contentAttrRelationships[$k]['attr_value']);
                            }

                            /*把字段放到 $content 中*/
                            $content[$v['attrName']['attr_enname']] = array(
                                'attr_name' => $v['attrName']['attr_name'],
                                'attr_value' => $contentAttrRelationships[$k]['attr_value'],
                            );
                        }
                        // P($contentAttrRelationships);
                    }

                    /*如果登录了，获取会员是否收藏、点赞*/
                    if($this->isLogin()){
                        $memberStar = new MemberStar;
                        $res = $memberStar::find()->select(['sflag'])
                                            ->where('app_id = :app_id and cflag=1 and contentid = :id and member_id = :mid', [':app_id' => $this->app_id, ':id' => $content_id, ':mid' => $this->memberInfo->member_id])
                                            ->all();
                        // P($res);
                        $content['star'] = false;
                        $content['praise'] = false;
                        if(!is_null($res)){
                            if(count($res) == 2){
                                $content['star'] = true;
                                $content['praise'] = true;
                            }
                            if(count($res) == 1){
                                if($res[0]->sflag == 1){
                                    $content['star'] = true;
                                }else if($res[0]->sflag == 2){
                                    $content['praise'] = true;
                                }
                            }
                        }
                    }

                    // $data = array(
                    //     'content' => $content,
                    //     'tags' => $tagsRelationships,
                    //     'attr' => $contentAttrRelationships
                    // );
                    // P($content);
                    return Tool::showRes([0, '获取成功'], $content);
                }else{
                    // $data = array(
                    //     'content' => [],
                    //     'tags' => [],
                    //     'attr' => []
                    // );
                    return Tool::showRes([0, '获取成功'], $content);
                };
            }
        }

        return Tool::showRes(ErrMap::getError(10005));
    }


    /*内容详情 增加点击量*/
    public function actionUpdatePreviewCount()
    {
        $id = isset($this->get['id'])?$this->get['id']:'';
        // echo $id;
        if($id){
            $isMobile = Tool::isMobile();//判断是否手机访问
            if($isMobile){
                Content::updateAllCounters(['mobile_preview_count' => 1], 'content_id = :id', [':id' => $id]);
            }else{
                Content::updateAllCounters(['pc_preview_count' => 1], 'content_id = :id', [':id' => $id]);
            }    
        };
        return Tool::showRes([0, '操作成功']);
    }

    /*内容详情 收藏列表*/
    public function actionStarList()
    {
        $id = isset($this->get['id'])?$this->get['id']:'';
        $sflag = isset($this->get['sflag'])?$this->get['sflag']:1;//如果为空的话，默认取收藏列表
        // echo $id;
        if($id and $sflag){
            // $MemberStar = MemberStar::find()->where()->al
            if(isset($this->get['page'])){
                $currPage = intval($this->get['page']?$this->get['page']:1);
            }else{
                $currPage = 1;
            }
            $pageSize = Tool::getPageSize();

            $memberStar = new MemberStar;
            $count = $memberStar::find()->where('app_id = :app_id and sflag = :sflag and cflag=1 and contentid = :id', [':app_id' => $this->app_id, ':sflag' => $sflag, ':id' => $id,])
                                    ->count();
            $memberStarList = $memberStar::find()
                            ->select(['contentid', 'nickname', 'headimgurl', 'comments', 'add_time',])
                            ->where('app_id = :app_id and sflag = :sflag and cflag=1 and contentid = :id', [':app_id' => $this->app_id, ':sflag' => $sflag, ':id' => $id,])
                            ->orderBy(['add_time' => SORT_DESC])
                            ->offset($pageSize*($currPage-1))->limit($pageSize)
                            ->asArray()->all();
            if($sflag != 3){//非评论，去掉评论字段
                foreach($memberStarList as $k => $v){
                    unset($memberStarList['comments']);
                }
            }
            // P($memberStarList);
            $res = array(
                'list' => $memberStarList,
                'pageInfo' => array(
                    'count' => intval($count),
                    'currPage' => $currPage,
                    'pageSize' => $pageSize,
                ),
            );
            return Tool::showRes([0, '获取成功'], $res);
        }
        return Tool::showRes(ErrMap::getError(10005));
    }


}
